import 'package:file_preview/file_preview.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:management/const/flags.dart';
import 'package:management/data/network/api/api.dart';
import 'package:shared_preferences/shared_preferences.dart';

class GlobalInit {
  static bool isFillInformation = false;

  GlobalInit._();
  static late SharedPreferences _prefs;
  static String _accessToken = '';
  static String _companyId = "0";
  static int _expireTime = 0;
  static String headImage = 'https://p3-passport.byteacctimg.com/img/user-avatar/e7b1c27411c5964953fb3b30f1e4877b~130x130.awebp';

  static Future init() async {
    WidgetsFlutterBinding.ensureInitialized();
    _prefs = await SharedPreferences.getInstance();
    EasyLoading.instance.toastPosition = EasyLoadingToastPosition.bottom;
    await FilePreview.initTBS(license: "initTbs");
    return Future.value();
  }

  static SharedPreferences getSp() {
    return _prefs;
  }

  static Future removeLoginStatus() async {
    _prefs.remove(SPFlag.password);
    _prefs.remove(SPFlag.accountEmail);
    _prefs.remove(SPFlag.accountPhone);
    _prefs.remove(SPFlag.refreshToken);
    _prefs.remove(SPFlag.accessToken);
  }

  static Future saveSpData(String flag, String data) async {
    if (flag == SPFlag.expiresIn) {
      _setExpireTime(data);
    }
    if (flag == SPFlag.accessToken) {
      _setAccessToken(data);
    }
    if (flag == SPFlag.companyId) {
      _setCompanyId(data);
    }
    await _prefs.setString(flag, data);
  }

  static String? getSpData(String flag) {
    return _prefs.getString(flag);
  }

  static Future removeSpData(String flag) async {
    await _prefs.remove(flag);
  }

  static String getCompanyId() {
    String? temp = _prefs.getString(SPFlag.companyId);
    if (temp != null) {
      _companyId = temp;
    }
    return _companyId;
  }

  // 只能在登录后调用
  static String getAccessToken() {
    // if (DateTime.now().millisecondsSinceEpoch > _expireTime) {
      String? refreshToken = getSpData(SPFlag.refreshToken);
      MyHttpClient.getRefreshByToken(refreshToken!).then((value) {
        if (value.code == 200) {
          saveSpData(SPFlag.expiresIn, value.data!.expiresIn!);
          saveSpData(SPFlag.accessToken, value.data!.accessToken!);
          return value.data!.accessToken;
        }
      });
    // }
    return _accessToken;
  }

  static int getExpireTime() {
    return _expireTime;
  }

  static _setExpireTime(String expire) {
    WidgetsFlutterBinding.ensureInitialized();
    int expireTime = int.parse(expire);
    _expireTime = DateTime.now().millisecondsSinceEpoch + expireTime * 1000;
  }

  static void _setAccessToken(String data) {
    WidgetsFlutterBinding.ensureInitialized();
    _accessToken = data;
  }

  static void _setCompanyId(String data) {
    WidgetsFlutterBinding.ensureInitialized();
    _companyId = data;
  }
}
